//
//  KLRevisePasswordViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/5/4.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLRevisePasswordViewController.h"
#import "FMDBTool.h"
#import "HemaConst.h"
#import "KLHelp.h"
#import "KLHttpAPI.h"
#import "JRToast.h"
#import "IdentifierValidator.h"

@interface KLRevisePasswordViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UILabel *pointOutLabel;
@property (weak, nonatomic) IBOutlet UITextField *changeMobileTF;
@property (weak, nonatomic) IBOutlet UIButton *changeMobileBtn;
@property (weak, nonatomic) IBOutlet UITextField *codeTF;
@property (weak, nonatomic) IBOutlet UILabel *codeLabel;

@property (nonatomic,strong) NSMutableDictionary *userDic;
@property (nonatomic,strong) NSTimer *timer;
@end

static int seconds;

@implementation KLRevisePasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化导航栏
    [self naveSet];
    seconds = 60;
    
    self.changeMobileBtn.layer.masksToBounds = YES;
    self.changeMobileBtn.layer.cornerRadius = 3;
    
    self.changeMobileTF.delegate = self;
    self.changeMobileTF.keyboardType = UIKeyboardTypeNumberPad;
    self.codeTF.delegate = self;
    self.codeTF.keyboardType = UIKeyboardTypeNumberPad;
    
    [FMDBTool openDataBase];
    self.userDic = [FMDBTool selectDataBase];
    NSString *mobileStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
    NSString *darkMobile = [NSString stringWithFormat:@"已绑定手机号:%@****%@",[mobileStr substringToIndex:3],[mobileStr substringFromIndex:7]];
    self.pointOutLabel.text = darkMobile;
    
    self.codeLabel.text = @"发送验证码";
    self.codeLabel.textColor = [UIColor colorWithRed:(float)8/255 green:(float)128/255 blue:(float)181/255 alpha:1];
    self.codeLabel.backgroundColor =  [UIColor colorWithRed:(float)255/255 green:(float)165/255 blue:(float)2/255 alpha:1];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [self.codeLabel addGestureRecognizer:tap];
}-(void)tap:(id)seder{
    //发送验证码
    BOOL isPhoneNumber = [IdentifierValidator isValid:IdentifierTypePhone value:self.changeMobileTF.text];
    if(isPhoneNumber == true){
        //请求验证码
        NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
        [KLHelp showHUDAddedTo:self.view title:@"请稍候..." details:nil animated:YES];
        [KLHttpAPI requestSecurityCodeWithUserName:username type:@"2" completionHandler:^(NSString *responseString) {
            NSLog(@"请求正常返回:%@",responseString);
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            NSDictionary *dic = [KLHelp dictionaryWithJsonString:responseString];
            NSString *successStr = [dic objectForKey:@"success"];
            if(successStr.integerValue == 1){
                //启动定时器
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
                
                [JRToast showWithText:@"验证码已发送" bottomOffset:50 duration:1.5];
                self.codeLabel.backgroundColor =  [UIColor lightGrayColor];
                self.codeLabel.userInteractionEnabled = NO;
                [self.view endEditing:NO];
            }else{
                [JRToast showWithText:[dic objectForKey:@"msg"]];
            }
        } errorHandler:^(NSString *error) {
            NSLog(@"请求错误;%@",error);
            [KLHelp hideAllHUDsForView:self.view animated:YES];
        }];
        
    }else{
        [JRToast showWithText:@"手机号格式有误" bottomOffset:50 duration:1.5];
    }
}-(void)updateLabel{
    seconds--;
    if(seconds >= 0){
        NSMutableAttributedString *secondsStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%d秒后重发",seconds]];
        
        [secondsStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
        [secondsStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"American Typewriter" size:17] range:NSMakeRange(0, 2)];
        
        self.codeLabel.attributedText = secondsStr;
    }else{
        self.codeLabel.backgroundColor =  [UIColor colorWithRed:(float)255/255 green:(float)165/255 blue:(float)2/255 alpha:1];
        self.codeLabel.userInteractionEnabled = YES;
        self.codeLabel.text = @"发送验证码";
        seconds = 60;
        [self.timer invalidate];
    }
}

#pragma mark - 点击更改
- (IBAction)changeMobile:(UIButton *)sender {
    [self.changeMobileTF resignFirstResponder];
    [self.codeTF resignFirstResponder];
    [UIView animateWithDuration:0.5 animations:^{
        self.view.frame = CGRectMake(0, 0, UI_View_Width, UI_View_Height);
    }];
    
    if(self.changeMobileTF.text.length == 0){
        [JRToast showWithText:@"手机号不能为空" bottomOffset:50 duration:1.5];
        return ;
    }
    if([IdentifierValidator isValid:IdentifierTypePhone value:self.changeMobileTF.text] == false){
        [JRToast showWithText:@"手机号格式有误" bottomOffset:50 duration:1.5];
        return ;
    }
    if(self.codeTF.text.length == 0){
        [JRToast showWithText:@"验证码不能为空" bottomOffset:50 duration:1.5];
        return ;
    }
    
    //验证验证码是否正确
    [KLHttpAPI requestCheckSecurityCodeWithUserName:[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"] securityCode:self.codeTF.text completionHandler:^(NSString *responseString) {
        NSLog(@"正常返回:%@",responseString);
        NSDictionary *dic = [KLHelp dictionaryWithJsonString:responseString];
        NSString *successStr = [dic objectForKey:@"success"];
        if(successStr.integerValue == 1){
            [KLHttpAPI requestChangeMobileWithToken:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] newPhoneNumber:self.changeMobileTF.text completionHandler:^(NSString *responseString) {
                NSLog(@"修改手机返回数据:%@",responseString);
                NSDictionary *changePhoneDic = [KLHelp dictionaryWithJsonString:responseString];
                NSString *successStr = [changePhoneDic objectForKey:@"success"];
                if(successStr.integerValue == 1){
                    [JRToast showWithText:@"修改成功"];
                    [[NSUserDefaults standardUserDefaults] setObject:self.changeMobileTF.text forKey:@"phoneNumber"];;
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    [JRToast showWithText:[changePhoneDic objectForKey:@"msg"]];
                }
            } errorHandler:^(NSString *error) {
                
            }];
        }else{
            [JRToast showWithText:[dic objectForKey:@"msg"]];
        }
        
    } errorHandler:^(NSString *error) {
        [JRToast showWithText:error];
    }];
    
}

#pragma mark -textfiled的代理
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [UIView animateWithDuration:0.5 animations:^{
        self.view.frame = CGRectMake(0, -100, UI_View_Width, UI_View_Height);
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [self.changeMobileTF resignFirstResponder];
    [self.codeTF resignFirstResponder];
    [UIView animateWithDuration:0.5 animations:^{
        self.view.frame = CGRectMake(0, 0, UI_View_Width, UI_View_Height);
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.changeMobileTF resignFirstResponder];
    [self.codeTF resignFirstResponder];
}

#pragma mark - 初始化导航栏
-(void)naveSet{
    self.title = @"修改手机号";
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
